<template>
  <div class="app-container">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-select v-model="dataForm.startTime" placeholder="时间">
          <el-option v-for="(name,key) in timeSelections" :key="key" :value="name" :label="key" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.msgTypes" placeholder="消息类型">
          <el-option value="" label="不限类型" />
          <el-option value="text,image,voice,shortvideo,video,news,music,location,link" label="消息" />
          <el-option value="event,transfer_customer_service" label="事件" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()" type="primary">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="text-gray">
      24小时内消息可回复。此后台展示消息有一分钟左右延迟，如需畅聊请使用
      <a href="https://mpkf.weixin.qq.com/" target="_blank">公众平台客服</a>
    </div>
    <div v-loading="dataListLoading">
      <div v-for="(msg,index) in dataList" :key="index" class="msg-item">
        <div class="avatar"><el-avatar shape="square" :size="60" :src="getUserInfo(msg.openid).headImgUrl" /></div>
        <div class="item-content">
          <div class="flex justify-between margin-bottom">
            <div class="text-cut">{{ getUserInfo(msg.openid).nickName || '--' }}</div>
            <div>{{ $moment(msg.createTime).calendar() }}</div>
            <div class="reply-btn">
              <div v-if="canReply(msg.createTime)" class="el-icon-s-promotion" @click="replyHandle(msg.openid)">回复</div>
            </div>
          </div>
          <wx-msg-preview :msg="msg" single-line />
        </div>
      </div>
    </div>
    <el-pagination :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalCount" layout="total, sizes, prev, pager, next, jumper" @size-change="sizeChangeHandle" @current-change="currentChangeHandle" />
    <!-- 弹窗, 消息回复 -->
    <wx-msg-reply ref="wxMsgReply" @success="onReplyed" />
  </div>
</template>

<script>
const TIME_FORMAT = 'YYYY/MM/DD hh:mm:ss'
import { fetchWxMsgList, wxUserList } from '@/api/wx'
export default {
  components: {
    WxMsgReply: () => import('./wx-msg-reply'),
    WxMsgPreview: () => import('@/components/Future/Wx/wx-msg-preview')
  },
  data() {
    return {
      timeSelections: {
        '近24小时': moment().subtract(1, 'days').format(TIME_FORMAT),
        '近3天': moment().subtract(3, 'days').format(TIME_FORMAT),
        '近7天': moment().subtract(7, 'days').format(TIME_FORMAT),
        '近30天': moment().subtract(30, 'days').format(TIME_FORMAT)
      },
      dataForm: {
        startTime: moment().subtract(1, 'days').format(TIME_FORMAT),
        msgTypes: ''
      },
      dataList: [],
      userDataList: [],
      pageIndex: 1,
      pageSize: 20,
      totalCount: 0,
      dataListLoading: false,
      dataListSelections: []
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      var parma = {
        'page': this.pageIndex,
        'limit': this.pageSize,
        'msgTypes': this.dataForm.msgTypes,
        'startTime': this.dataForm.startTime,
        'sidx': 'create_time',
        'order': 'desc'
      }
      fetchWxMsgList(parma).then(response => {
        this.dataList = response.records
        this.totalCount = response.total
        this.refreshUserList(this.dataList)
        this.dataListLoading = false
      })
    },
    refreshUserList(msgList) {
      if(!msgList){
        return
      }
      let openIdList = msgList.map(msg => msg.openid).filter(openId => !this.userDataList.some(u => u.openId == openId))
      if (!openIdList.length) return
      openIdList = Array.from(new Set(openIdList))// 去重
      wxUserList(openIdList).then(response => {
        this.userDataList = this.userDataList.concat(response)
      })
    },
    getUserInfo(openId) {
      return this.userDataList.find(u => u.openId == openId) || { nickName: '--', headImgUrl: '' }
    },
    // 是否可回复，24小时内可回复
    canReply(time) {
      return time > moment().unix().valueOf() - 24 * 60 * 60
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 回复消息
    replyHandle(openId) {
      this.$nextTick(() => {
        this.$refs.wxMsgReply.init(openId)
      })
    },
    onReplyed(replyMsg) {
      this.dataList.unshift({
        openId: replymsg.openid,
        msgType: replyMsg.replyType,
        detail: {
          content: replyMsg.replyContent
        },
        inOut: 1,
        createTime: new Date()
      })
    }
  }
}
</script>
<style scoped>
.msg-item{
    border: 1px solid #DCDFE6;
    display: flex;
    justify-content: flex-start;
    align-items: top;
    margin-top: 20px;
    padding: 10px 20px;
}
.avatar{
    flex: 0;
    display: inline-block;
    min-width: 60px;
    margin-right: 20px;
}
.item-content{
    flex: 1;
    line-height: 20px;
    max-width: 100%;
    overflow: hidden;
}
.reply-btn{
    width: 50px;
}
</style>
